package com.xd.core.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xd.core.note.ICacheService;
import com.xd.core.system.entity.CityInfo;
import com.xd.core.system.mapper.CityInfoMapper;
import com.xd.core.system.service.ICityInfoService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author SJ
 * @since 2023-03-28
 */
@Service
public class CityInfoServiceImpl extends ServiceImpl<CityInfoMapper, CityInfo> implements ICityInfoService {
    @Resource
    private ICacheService cacheService;


    @Override
    public List<CityInfo> getCity(boolean head) {
        return cacheService.city(head);
    }

    /*
     * 获取城市分类
     * */
    public static Map<Integer, List<CityInfo>> getMap(List<CityInfo> MapCodeVoList) {
        Map<Integer, List<CityInfo>> map = new HashMap<>();
        for (CityInfo mapcode : MapCodeVoList) {
            Integer parentId = mapcode.getPid();

            if (map.containsKey(parentId)) {
                List<CityInfo> childlist = map.get(parentId);
                childlist.add(mapcode);
            } else {
                List<CityInfo> childlist = new ArrayList<>();
                childlist.add(mapcode);
                map.put(parentId, childlist);
            }
        }
        return map;
    }

    /*
     * 获取城市树状结构
     * */
    public static List<CityInfo> getCityChild(List<CityInfo> cityInfos, Map<Integer, List<CityInfo>> map) {
        for (CityInfo cityInfo : cityInfos) {
            Integer id = cityInfo.getId();
            List<CityInfo> childs = map.get(id);
            if (!CollectionUtils.isEmpty(childs)) {
                for (CityInfo child : childs) {
                    cityInfo.setCityChild(childs);
                    getCityChild(childs, map);
                }
            }
        }
        return cityInfos;
    }
}

